<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #quan {
            margin: 0 auto;
            width: 300px;
            height: 300px;
            line-height: 300px;
            text-align: center;
            font-size: 20px;
            background-color: skyblue;
        }
    </style>
</head>

<body>
    <!-- 防抖是控制次数，节流是控制频率 -->
    <div id="quan"></div>
    <script>
        let box = document.getElementById('quan')
        let i = 0
        box.addEventListener('mousemove', throttle(() => {
            i++;
            box.innerHTML = i
        }, 2000))

        // 时间戳版本
        // function throttle(fn, wait = 1000) {
        //     let preTime = 0
        //     return function () {
        //         let ctx = this
        //         let args = arguments
        //         // 输出和防抖类似
        //         console.log(this)
        //         console.log(arguments)
        //         let nowTime = new Date().getTime()
        //         if (nowTime - preTime > wait) {
        //             fn.apply(ctx, args)
        //             preTime = nowTime
        //         }
        //     }
        // }

        // 定时器版
        function throttle(fn, wait = 1000) {
            let timer = null
            return function () {
                let ctx = this
                let args = arguments
                console.log(this)
                console.log(arguments)
                if (!timer) {
                    timer = setTimeout(() => {
                        fn.apply(ctx, args)
                        timer = null
                    }, wait)
                }
            }
        }
    </script>
</body>

</html>